package com.tiandang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tiandang.core.response.CommonReturnType;
import tiandang.core.service.FileStore;
import tiandang.core.utils.DomainUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class UploadController {

  @Autowired
  private FileStore fileStore;

  @PostMapping("/upload")
  public Object upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request)
    throws Exception {

    if (file != null) {
      // 先保存文件,取到返回值,再将记录插入数据库,记录在picture表里
      Map<String, Object> resultMap = new HashMap<>();
      Map map = fileStore.uploadBy(file);
      String fileName = (String) map.get("fileName");
      String filePath = (String) map.get("filePath");

      String fileUrl = DomainUtil.getDomain(request) + filePath;

      resultMap.put("fileName", fileName);
      resultMap.put("fileUrl", fileUrl);
      return CommonReturnType.success(resultMap);

    } else {
      return CommonReturnType.error(-1, "文件不存在");
    }

  }

}
